<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use EasyWeChat\Factory;
use think\Session;

class Activity extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public $config = [
        'app_id' => 'wx1f8725eef4e232a4',
        'secret' => '422171ef36ac1a93c055d0191cdfb751',
        'oauth' => [
            'scopes'   => ['snsapi_userinfo'],
            'callback' => '/index/Activity/oauth',
        ]
    ];
    public $app;

    public function _initialize()
    {
        parent::_initialize();
        $this->app = Factory::officialAccount($this->config);
    }

    public function oauth()
    {
        $oauth = $this->app->oauth;
        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();

        $_SESSION['wechat_user'] = $user->toArray();
        Session::set('wechat_user',$user->toArray());
        $targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];

        header('location:'. $targetUrl); // 跳转到 user/profile
        return $response = $this->app->oauth->scopes(['snsapi_userinfo'])
            ->redirect();
    }

    public function breaks()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            $oauth = $this->app->oauth;
            // 未登录
            if (empty($_SESSION['wechat_user'])) {

                $_SESSION['target_url'] = '/index/Activity/breaks';
//            return $oauth->redirect();
                // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用
                $oauth->redirect()->send();exit;
            }
            // 已经登录过
            $user = $_SESSION['wechat_user'];
            $this->app->jssdk->setUrl('');
            $jssdk = $this->app->jssdk->buildConfig(['chooseWXPay'], $debug = false, $beta = false, $json = true);
            $this->view->assign('jssdk',$jssdk);
            return $this->view->fetch();
        }
        return $this->view->fetch('activity/index');
    }

    public function recruit()
    {

        return $this->view->fetch();
    }

}
